<template>
  <div style=" height: 100vh;position: relative;">
    <div class="login_title">绑定</div>
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="0px" class="demo-ruleForm">
      <el-form-item prop="mobile">
        <span class="svg-container">
          <i class="el-icon-phone"></i>
        </span>
        <el-input placeholder="请输入手机号" clearable v-model="ruleForm.mobile" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item prop="code">
        <span class="svg-container">
          <i class="el-icon-chat-dot-square"></i>
        </span>
        <el-input placeholder="请输入验证码" maxlength="6" clearable v-model="ruleForm.code" autocomplete="off"
          style="width: 69%;">
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button :disabled="!CodeType" :type="CodeType ? 'success' : 'info'" @click="sendCode('ruleForm')"
          class="OutCode">{{ CodeText }}
        </el-button>
      </el-form-item>
    </el-form>
    <div class="login">
      <el-button type="primary" @click="submitForm('ruleForm')" class="login_btn">确认绑定</el-button>
    </div>
  </div>
</template>

<script>
import { PAGE_BASE_URL } from '@/config'
import store from '@/store'
import { setToken } from '@/utils/auth'

import { sendCode, verification, wechat, getToken, binding, openidLogin } from '@/api/newuser'
import { async } from 'q';
export default {
  components: {
  },
  data() {
    var validateNumber = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号'));
      } else {
        if (!(/^1[3456789]\d{9}$/.test(value))) {
          callback(new Error('请输入正确的手机号'));
        } else {
          callback();
        }
      }
    };
    var validateCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入验证码'));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        mobile: '',
        code: '',
      },
      rules: {
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validateNumber, trigger: 'blur' }
        ],
        code: [
          // { required: true, message: '请输入验证码', trigger: 'blur' },
          // { validator: validateCode, trigger: 'blur' }
        ],
      },
      CodeType: true,
      CodeText: '发送验证码',
    };
  },
  mounted() {
    this.wechat()
  },
  methods: {
    wechat() {
      // console.log(localStorage.getItem('userId'));
      // console.log(sessionStorage.getItem('userId'));
      // console.log(window.location.href, 'window.location.href');
      if (window.location.href.indexOf('code') === 0 || window.location.href.indexOf('code') <= 0) {
        // window.location.replace(`http://yzsq.oramage.com/#/web/small/login`)
        wechat().then(res => {
          window.location.replace(res.url)
        })
      } else {
        function getQueryString(name) {
          const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
          const r = window.location.search.substr(1).match(reg)
          if (r != null) {
            return encodeURIComponent(r[2])
          } else {
            return null
          }
        }
        const code = getQueryString('code')

        // console.log(code, 'code');
        getToken({ code: code }).then(res => {
          // console.log(res, 'openid');
          localStorage.setItem('openid', res.openid)
          // let code_url = '?code=' + code
          //window.location.href 中去除code_url
          // let url = window.location.href.replace(code_url, '')
          // window.location.replace(url)
          openidLogin({ openid: res.openid }).then(async res => {
            // console.log(res, 'openidLogin');
            if (res.id) {
              //将res存入localStorage
              localStorage.setItem('data', JSON.stringify(res))
              // console.log(JSON.parse(localStorage.getItem('data')))
              localStorage.setItem('userId', res.id)
              // console.log(res, 'resbinding');
              let demo = await store.commit('user/SET_TOKEN', res.token)
              localStorage.setItem('token', res.token)
              setToken(res.token)
              //延迟跳转
              setTimeout(() => {
                // this.$router.push({ path: '/web/small/Waitvisit' })
                window.location.replace('https://shundeip.com/#/web/small/Waitvisit')
                // console.log(demo, 'demo', store.getters.token);
              }, 50)
            } else {
              // this.$router.push({ path: '/web/small/login' })
            }
          })
        })
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          verification(this.ruleForm).then(res => {
            // console.log(res, 'res');
            binding({
              openid: localStorage.getItem('openid'),
              mobile: this.ruleForm.mobile,
            }).then(async res => {
              //将res存入localStorage
              localStorage.setItem('data', JSON.stringify(res))
              // console.log(JSON.parse(localStorage.getItem('data')))
              localStorage.setItem('userId', res.id)
              // console.log(res, 'resbinding');
              let demo = await store.commit('user/SET_TOKEN', res.token)
              localStorage.setItem('token', res.token)
              setToken(res.token)
              //延迟跳转
              setTimeout(() => {
                this.$router.push({ path: '/web/small/Waitvisit' })
                // console.log(demo, 'demo', store.getters.token);
              }, 50)
            })

            // getters.token = '3bcbcf93da59f3e0c95e0c3d90f11112-0'
            // this.$store.commit(SET_TOKEN, '3bcbcf93da59f3e0c95e0c3d90f11112-0')
            // console.log(this.$store,'token');
            // setToken('3bcbcf93da59f3e0c95e0c3d90f11112-0');
            // sessionStorage.setItem("token", '3bcbcf93da59f3e0c95e0c3d90f11112-0');
            // setToken(sessionStorage.getItem("token"));
          })
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    },
    sendCode(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            let demo = await sendCode({ mobile: this.ruleForm.mobile }).then(res => {
              // console.log(res)
              this.CodeType = false;
              this.CodeText = '60s';
              let time = 60;
              let timer = setInterval(() => {
                time--;
                this.CodeText = time + 's';
                if (time <= 0) {
                  clearInterval(timer);
                  this.CodeType = true;
                  this.CodeText = '发送验证码';
                }
              }, 1000);
            })
          } catch (e) {
            this.$message.error(e.message)
          }
        } else {
          this.$message.error(e.message)
          return false;
        }
      });

    }
  },
};
</script>

<style lang="less" scoped>
::v-deep .el-input__inner {
  padding: 0 30px;
}

.svg-container {
  position: absolute;
  left: 7px;
  z-index: 10;
  font-size: 16px;
}

.login_title {
  font-weight: bold;
  font-size: 28px;
  position: absolute;
  top: 21%;
  left: 50%;
  transform: translate(-50%, 0%);
}

.demo-ruleForm {
  width: 100%;
  padding: 0 10px;
  position: absolute;
  top: 32%;
  left: 50%;
  transform: translate(-50%, 0%);
}

.login {
  padding: 0 10px;
  padding: 0 10px;
  position: absolute;
  left: 0;
  right: 0;
  top: 400px;

  .login_btn {
    width: 100%;
  }
}

.OutCode {
  position: absolute;
  right: 0;
  top: -62px;
  width: 110px;
}

@media (max-width:750px) {}
</style>